package filter;

import java.io.IOException;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 
 * 浏览器端Cookie更新过滤器，Cookie主要包括用户名信息。
 * 
 * @author  xmwang
 * 
 */

public class StatusUpdateFilter implements Filter{

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.setContentType("text/html");
    String name = (String) req.getSession().getAttribute("name");
    if(name != null) {
      resp.addCookie(new Cookie("name", name)); // 用户
    }else {
      resp.addCookie(new Cookie("name", "")); // 游客
    }
    chain.doFilter(request, response);
  }
}
